package MediaOnline.GUI;

/*
 * Nahi media Player class
 * 
 * Version information 2.5 fixed
 *
 * Date 30/07/2012
 * 
 * Copyright notice nahuroid team 
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import MediaOnline.Adapter.Quality_Film_Adapter;
import MediaOnline.Data.ListFilmForMedia;
import MediaOnline.Data.filmDetail;
import MediaOnline.General.RegistrySession;
import MediaOnline.General.ScreenResolution;
import MediaOnline.General.paramConst;
import MediaOnline.VideoPlayer.Bookmark;
import MediaOnline.VideoPlayer.LikeMovie;
import MediaOnline.VideoPlayer.NahiDialog;
import MediaOnline.WebService.SessionRegister;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class Nahi_MediaActivity extends Activity implements
		OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener,
		SurfaceHolder.Callback, OnErrorListener, Runnable {
	/** Called when the activity is first created. */
	final Context context = this;
	private static final String TAG = "MediaPlayer";
	private int mVideoWidth;
	private int mVideoHeight;
	private MediaPlayer mMediaPlayer;
	private SurfaceView mPreview;
	private SurfaceHolder holder;
	private String path, pathLink;
	private SeekBar seekBar;
	private ImageButton btnList, soundController, btnlike, btnPlayer, btnBack,
			btnNext, btnLight, resize, btnQuality_film;
	private Button btnsave, btnclear;
	private TextView txtPercent, txtPercentEnd, txtTextZoom;
	private boolean flag, isLike = false;
	private boolean mIsVideoSizeKnown = false;
	private int iProgress = 0;
	private boolean mIsVideoReadyToBePlayed = false;
	private int total, volumePrgress = 4;
	private Handler handler;
	private LinearLayout layoutSeekbar, layoutTop, layoutControl;
	private AudioManager audioManager = null;
	private SeekBar seekBarVolume = null;
	private boolean flagSound, flagShow = true;
	private Thread currentThread;
	private ArrayAdapter<String> nahiAdapter;
	private ListView mainListView = null, list_video;
	private RelativeLayout layoutLike;
	private TextView filmName;
	private LikeMovie liked;
	private Bookmark bookAudio, bookVideo, currentSizeScreen;
	private filmDetail filmInfo;
	private int vLight = 1, vSize = 1;
	private TappableSurfaceView surface;
	public int screen = -1;
	private String mVideoPath;
	private int height, weith, durationFilm;
	protected Animation animation;
	private ProgressBar progressBarWait;

	protected HttpClient httpclient;
	public static HttpPost httppost = null;
	protected ListView quality_of_films;
	public static Quality_Film_Adapter adapter_qlt_film;
	protected ArrayAdapter<String> adapterQualityVideo;
	public static ArrayList<String> arrListvideo;
	public static ArrayList<String> arrListvideoUrl;
	private RelativeLayout relay;
	protected Spinner spn_Quality_Films;
	ArrayList<String> lstQuality_Films = new ArrayList<String>();
	private Animation mSlideBottomUpAnimation;
	private Animation mSlideBottomDownAnimation;
	private Animation mSlideTopDownAnimation;
	private Animation mSlideTopUpAnimation;
	
	private void updateFullscreenStatus(boolean flag) {
		if (flag) {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		} else {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.media2);
		// Tắt chế độ sleep
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		httpclient = new DefaultHttpClient();
		/* Khai bao giao dien. Khoi tao cac layout va button */
		relay = (RelativeLayout) findViewById(R.id.relaycover);
		filmName = (TextView) findViewById(R.id.filmname);
		surface = (TappableSurfaceView) findViewById(R.id.surface_view);

		holder = surface.getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		holder.setFixedSize(TappableSurfaceView.width,
				TappableSurfaceView.height);
		// khai bao cac nut bam
		btnlike = (ImageButton) findViewById(R.id.like);
		txtPercent = (TextView) findViewById(R.id.percent);
		txtPercentEnd = (TextView) findViewById(R.id.percent1);
		seekBar = (SeekBar) findViewById(R.id.slider);
		btnPlayer = (ImageButton) findViewById(R.id.play);
		btnList = (ImageButton) findViewById(R.id.list_back);
		btnLight = (ImageButton) findViewById(R.id.light);
		txtTextZoom = (TextView) findViewById(R.id.txtZoomText);
		btnQuality_film = (ImageButton) findViewById(R.id.quality_film);
		// khai bao 2 linearLayout
		layoutSeekbar = (LinearLayout) findViewById(R.id.layoutSeekbar);
		layoutTop = (LinearLayout) findViewById(R.id.layoutTop);
		layoutControl = (LinearLayout) findViewById(R.id.layoutControl);
		soundController = (ImageButton) findViewById(R.id.volume);
		layoutTop.setVisibility(View.GONE);
		// Typeface font = Typeface.createFromAsset(getAssets(),
		// "font/Chantelli_Antiqua.ttf");
		seekBarVolume = (SeekBar) findViewById(R.id.volumeSeekBar);
		layoutLike = (RelativeLayout) findViewById(R.id.layoutLike);
		btnsave = (Button) findViewById(R.id.btnSave);
		btnclear = (Button) findViewById(R.id.btnClear);
		mainListView = (ListView) findViewById(R.id.list);
		progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
		resize = (ImageButton) findViewById(R.id.resize);
		// danh sach video phim tap
		// list_video=(ListView)findViewById(R.id.list_video);

		/*lstQuality_Films.add("Low");
		lstQuality_Films.add("Medium");
		lstQuality_Films.add("hight");*/
		// Lấy danh sách chất lượng cho video
		
		quality_of_films = (ListView) findViewById(R.id.lst_quality);
		quality_of_films.setVisibility(View.GONE);
		adapter_qlt_film = new Quality_Film_Adapter(Nahi_MediaActivity.this,
				lstQuality_Films);
		quality_of_films.setAdapter(adapter_qlt_film);

		audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		seekBarVolume.setMax(audioManager
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
		seekBarVolume.setProgress(audioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC));
		initVolumeController(volumePrgress, seekBarVolume);
		// ------------ket thuc ham khoi tao volume----------------------
		// Tạo animation cho tên phim
		animation = new TranslateAnimation(0, 20, 0, 0);

		animation.setDuration(5000);

		animation.setRepeatMode(Animation.RESTART);

		animation.setRepeatCount(Animation.INFINITE);

		filmName.startAnimation(animation);

		filmName.setSelected(true);
		// filmName.setTypeface(font);
		layoutSeekbar.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				showController();
				handler.removeCallbacks(hideController);
				hideController();
			}
		});
		//
		layoutControl.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				showController();
				handler.removeCallbacks(hideController);
				hideController();
			}
		});
		//

		btnPlayer.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				showController();
				handler.removeCallbacks(hideController);
				hideController();
			}
		});
		//

		layoutTop.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				showController();
				handler.removeCallbacks(hideController);
				hideController();
			}
		});
		//
		// arrListvideo=new ArrayList<String>();
		relay.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (layoutControl.getVisibility() == View.GONE) {
					showControlOverlays();
					showController();
					handler.removeCallbacks(hideController);
					hideController();

				} else {
					hideControlOverlays();
					hideAllLayout();
				}

			}
		});
		quality_of_films.setVisibility(View.GONE);
		// an hien chat luong phim
		btnQuality_film.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (quality_of_films.getVisibility() == View.VISIBLE) {

					quality_of_films.setVisibility(View.GONE);
				} else {

					quality_of_films.setVisibility(View.VISIBLE);
				}
			}
		});

		// chon video tu danh sach
		// adapterListVideo=new ArrayAdapter<String>(Nahi_MediaActivity.this,
		// android.R.layout.simple_list_item_1, ListFilmForMedia.lstFilms);
		// adapterListVideoUrl=new ArrayAdapter<String>(Nahi_MediaActivity.this,
		// android.R.layout.simple_list_item_1, ListFilmForMedia.lstFilmUrl);
		// list_video.setAdapter(adapterListVideo);
		// refreshListVideo();
		/*
		 * list_video.setOnItemClickListener(new OnItemClickListener() {
		 * 
		 * public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		 * long arg3) { // TODO Auto-generated method stub
		 * 
		 * } });
		 */
		/*	Bat dau phan xu ly gia dien hien an */
		initAnimations() ;
		double ratioScreen = ScreenResolution.getInstance(
				Nahi_MediaActivity.this).getScreen();
		if (ratioScreen < 5) {
			screen = 1;
		} else if ((ratioScreen >= 5) && (ratioScreen <= 11)) {
			//	neu man hinh lon hon bang 5" thi mm=2
			screen = 2;
		} else if ((ratioScreen >= 11) && (ratioScreen <= 32)) {
			//	man hinh tu 11" den 32" thi mm=3
			screen = 3;
		} else {
			//	man hinh lon hon 32" thi mm=4 tuong duong voi 1080
			screen = 4;
		}

		// --------------------------------------
		// Khởi tạo bookmart cho volume và bookmark video
		bookAudio = new Bookmark(this);
		bookVideo = new Bookmark(this);
		currentSizeScreen=new Bookmark(this); 
		currentSizeScreen.addBookMark("screenDefault", screen);
		// Lấy thông tin đường dẫn từ intent
		Intent playOtherFile = getIntent();
		String filepath = "";

		try {
			// File path có 2 loại, file trên thẻ sd thì là file trực tiếp,
			// Tách link
			String s = playOtherFile.getData().toString();
			int idx = s.indexOf("?st=");
			// Nếu có chữ "?st=", tức là phim trên hd Ha Noi
			if (idx != -1) {
				filepath = s;
			}
			// Nếu không có chữ "?st=", tức là phim trên thẻ nhớ
			else {
				filepath = playOtherFile.getData().getPath();
			}

		} catch (Exception e) {
			// TODO: handle exception
			Log.d("GetLINk LOg", e.getStackTrace().toString());
		}
		// Nếu có path file (mở file trên sd card) thì play file đó
		if (!filepath.equals("")) {
			pathLink = filepath;
		}
		// Không thì play file online
		else {
			// Lay thong tin video tu ben list tra ve
			pathLink = getIntent().getExtras().getString("Link");

		}

		Log.d("Path link:::::::", pathLink);
		// -------------Khởi tạo likedlist
		liked = new LikeMovie(this);
		nahiAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice,
				liked.getList());
		mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		mainListView.setAdapter(nahiAdapter);

		// ---------------kết thúc khởi tạo likedList
		mMediaPlayer = new MediaPlayer();
		path = pathLink;
		handler = new Handler();
		try {
			mMediaPlayer.setDataSource(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Nếu đang play file trên sd card thì không hiện phim name và ngược lại
		if (filepath.equals("")) {
			filmName.setText(filmDetail.FilmNameChinh.toString());
		}

		// Ẩn các trạng thái
		hideController();

		/**
		 * Xu ly cac button Play, Back, list, Previous, sound va seekbar Cac
		 * button previous va Back, like se duoc xu dung tu class
		 * LstVideoViewInfo, class nay duoc xem nhu mot controller
		 * 
		 * */
		// Xử lý button resize video
		resize.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				setRatioVideoSize();
			}
		});

		// nút play video
		btnPlayer.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mMediaPlayer.isPlaying()) {
					if (mMediaPlayer != null) {
						mMediaPlayer.pause();
						// Changing button image to play button
						btnPlayer.setImageResource(R.drawable.btn_play);

					}
				} else {
					// Resume video
					if (mMediaPlayer != null) {
						mMediaPlayer.start();
						// Changing button image to pause button
						btnPlayer.setImageResource(R.drawable.btn_pause);
					}
				}
				// Bat dau choi video
			}
		});
		//

		/**
		 * Bắt đầu xử lý các nút Lưu, xóa, và lựa chọn bài hát của tính năng
		 * phim yêu thích
		 * */
		// bat đầu các nút xử lý danh sách yêu thích
		btnsave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) { // TODO Auto-generated method stub
				liked.addLiked(filmInfo.Url, filmInfo.FilmNameChinh);
				/*
				 * notifyLike.setText("Bạn vừa lưu phim " + " " +
				 * filmInfo.FilmNameChinh + "" + "vào danh sách");
				 */
				updateLikeList();
				btnsave.setVisibility(View.VISIBLE);
			}
		});
		// xóa khỏi danh sách
		btnclear.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				Integer[] deleteIdx = getDeletedItems();
				liked.deleteLikes(deleteIdx); // xoa cac id cua phim duoc check
				updateLikeList(); // cap nhat list moi nhat

			}
		});

		// Phuong thuc them video vao danh sach ua thich
		btnlike.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isLike == false) {
					layoutLike.setVisibility(View.VISIBLE);
					isLike = true;
				} else {
					isLike = false;
					layoutLike.setVisibility(View.GONE);

				}
			}
		});

		// thiet lap long press cho like
		btnlike.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				liked.addLiked(filmInfo.Url, filmInfo.FilmNameChinh);
				resumeDialog();
				return false;
			}
		});

		//
		mainListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				// addBookMark(filmInfo.Url, mMediaPlayer.getCurrentPosition());
				bookVideo.addBookMark(filmInfo.Url,
						mMediaPlayer.getCurrentPosition());
				mMediaPlayer.pause();
				mMediaPlayer.stop();
				mMediaPlayer.release();
				path = liked.getId(arg2);
				startVideo(bookVideo.getBookmark(path));
				return true;
			}
		});

		// mute/unmute sound
		soundController.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				if (flagSound) {
					audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
							bookAudio.getBookmark("Audio"), 0);

					seekBarVolume.setProgress(bookAudio.getBookmark("Audio"));
					flagSound = false;

					soundController.setImageResource((R.drawable.volume));
				} else {
					audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0,
							0);
					bookAudio.addBookMark("Audio", volumePrgress);
					seekBarVolume.setProgress(0);
					soundController.setImageResource((R.drawable.volumemute));
					flagSound = true;

				}

			}

		});

		// xem danh sach video hien co
		btnList.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					bookVideo.addBookMark(filmInfo.FilmID,
							mMediaPlayer.getCurrentPosition());
					stopThread();

				} catch (Exception ex) {
					Log.d("TAG:::::::::_______", "can't send Intent");
					ex.getMessage();

				}
			}
		});

		// Seekbar listener
		seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				seekBar.setSecondaryProgress(seekBar.getProgress());
			}

			//
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				if (fromUser) {

					mMediaPlayer.seekTo(progress);
					seekBar.setProgress(progress);
					txtTextZoom.setVisibility(View.VISIBLE);

					int millisCurrent = progress;
					int hours = millisCurrent / (1000 * 60 * 60);
					int minutes = (millisCurrent % (1000 * 60 * 60))
							/ (1000 * 60);
					int seconds = ((millisCurrent % (1000 * 60 * 60)) % (1000 * 60)) / 1000;
					if (hours > 0) {
						txtTextZoom.setText(String.format("%02d:%02d:%02d",
								hours, minutes, seconds));
					} else {
						txtTextZoom.setText(String.format("%02d:%02d", minutes,
								seconds));
					}
				} else {
					txtTextZoom.setVisibility(View.GONE);

				}
			}

		});// ket thuc seekbar
			// Điều chỉnh đèn
		btnLight.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				// notifyLike.setText("Be ngang" + String.valueOf(mVideoWidth) +
				// " Cao" +String.valueOf(mVideoHeight));
				// TODO Auto-generated method stub
				Log.d("TAG:::::::::_______", String.valueOf(vLight));
				setLight();
				switch (vLight) {
				case 0:
					btnLight.setImageResource(R.drawable.btn_llight);
					break;
				case 1:
					btnLight.setImageResource(R.drawable.btn_nlight);
					break;
				case 2:
					btnLight.setImageResource(R.drawable.btn_hlight);
					break;
				default:
					break;
				}
				Log.d("TAG:::::::::_______", String.valueOf(vLight));
			}
		});
		// tao mot luong de chay seekbar song song

		currentThread = new Thread(this);
		currentThread.start();

	}

	// -----------------Ket thuc xu ly button
	/**
	 * Cac phuong thuc bao gom startVideo, va cac ham override cua MediaPlayer
	 * ham goi chay video, cac ham khoi tao seekbar am thanh
	 */
	// Phuong thuc nay tra ve mang nhung video yeu thich muon xoa khoi ds
	private Integer[] getDeletedItems() {
		ArrayList<Integer> deleteIdx = new ArrayList<Integer>();
		int count = this.mainListView.getAdapter().getCount();

		for (int i = 0; i < count; i++) {
			if (this.mainListView.isItemChecked(i)) {
				deleteIdx.add(i);
			}
		}
		Integer[] arrX = new Integer[deleteIdx.size()];
		arrX = deleteIdx.toArray(arrX);
		return arrX;
	}// ket thuc ham

	// Kiem tra bookmark hien tai
	public boolean checkVideoBookMark() {
		if (bookVideo.getBookmark(filmInfo.FilmID) != 0) {
			iProgress = bookVideo.getBookmark(filmInfo.FilmID);

			return true;
		} else {

			iProgress = 0;
			return false;
		}
	}// ket thuc kiem tra

	// Tao thong bao nguoi dung muon resume video
	public void resumeDialog() {
		if (checkVideoBookMark()) {
			NahiDialog ndg = new NahiDialog(); // khoi tao doi tuong Nahidialog
			if (ndg.showConfirmDialog(context, R.drawable.infomation,
					"Xem tiếp...", "Bạn có muốn xem tiếp đoạn trước?")) {
				startVideo(iProgress);
			} else { // neu nguoi dung khong chon bookmark truoc do
				seekBar.setProgress(0);
				startVideo();
			}
		} else { // neu video nay khong co bookmark truoc do
			seekBar.setProgress(0);
			startVideo();
		} // ket thuc dieu kien kiem tra bookmark video

	}// resume bookmark

	// Refresh lai listlike khi co su thay doi
	private void updateLikeList() {
		new AdapterHelper().update(nahiAdapter, liked.getList());
		nahiAdapter.notifyDataSetChanged();

	}

	// start video dua vao iCurrentvideo hien tai
	public void startVideo() {
		if (flag) {

			btnPlayer.setVisibility(View.VISIBLE);
			mMediaPlayer.start();
		} else {
			playVideo(path, 0);
		}

		total = mMediaPlayer.getDuration();
		seekBar.setMax(total);
		btnPlayer.setVisibility(View.GONE);

	}// ket thuc ham

	// StartVideo voi tham so truyen vao la bookmark cua video muon xem
	public void startVideo(int bookmarkTime) {
		if (flag) {

			btnPlayer.setVisibility(View.VISIBLE);
			mMediaPlayer.start();
		} else {
			playVideo(path, bookmarkTime);
		}
		total = mMediaPlayer.getDuration();
		seekBar.setMax(total);
		btnPlayer.setVisibility(View.GONE);

	}// ket thuc ham

	// Tao phuong thuc de chay video
	private void playVideo(String path, int seekto) {

		doCleanUp();
		try {
			// Create a new media player and set the listeners
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setDataSource(path);
			mMediaPlayer.setDisplay(holder);
			try {
				mMediaPlayer.prepare();
			} catch (Exception e) {
				finish();
			}
			mMediaPlayer.setOnBufferingUpdateListener(this);
			mMediaPlayer.setOnCompletionListener(this);
			mMediaPlayer.setOnPreparedListener(this);
			mMediaPlayer.seekTo(seekto);
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

		} catch (Exception e) {
			Log.e(TAG, "error: " + e.getMessage(), e);
		}
	}// Ket thuc phuong thuc play video

	// Tao mot handler de set su kien seekbar chay song song voi video
	private Handler threadHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int millisCurrent = (int) ((msg.what));
			int hours = millisCurrent / (1000 * 60 * 60);
			int minutes = (millisCurrent % (1000 * 60 * 60)) / (1000 * 60);
			int seconds = ((millisCurrent % (1000 * 60 * 60)) % (1000 * 60)) / 1000;
			if (hours > 0) {
				txtPercent.setText(String.format("%02d:%02d:%02d", hours,
						minutes, seconds));
			} else {
				txtPercent
						.setText(String.format("%02d:%02d", minutes, seconds));

			}
			seekBar.setProgress(msg.what);
			durationFilm = millisCurrent;

		}
	};// ket thuc handler

	// Thread tracking vi tri cua seekbar
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (mMediaPlayer != null) {
				int currentPosition = mMediaPlayer.getCurrentPosition();
				Message msg = new Message();
				msg.what = currentPosition;
				String timer = String.valueOf(msg.what);
				msg.obj = timer;
				// -------------------------------------
				threadHandler.sendMessage(msg);

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
					System.out.println("interrupt exeption" + e);
				}

			}

		}

		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("My exeption" + e);
		}

	}// ket thuc tracking thread method

	// ket thuc luong thread seekbar
	public void stopThread() {
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			threadHandler.removeCallbacks(currentThread);
			finish();
		}

	}//

/*	// thay doi kich thuoc man hinh phu hop
	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		// TODO Auto-generated method stub
		Log.e(TAG, "invalid video width(" + width + ") or height(" + height
				+ ")");
		Log.v(TAG, "onVideoSizeChanged called");
		if (width == 0 || height == 0) {
			Log.e(TAG, "invalid video width(" + width + ") or height(" + height
					+ ")");
			return;
		}
		mIsVideoSizeKnown = true;
		mVideoWidth = width;
		mVideoHeight = height;

		if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
			startVideoPlayback();
		}
	}
*/
	/* Thay đổi kích thước video 16:9 hoặc fullscreen */
	private void setVideoSize(int width, int height) {
		android.view.ViewGroup.LayoutParams lp = surface.getLayoutParams();
		lp.height = height;
		lp.width = width;
		surface.setLayoutParams(lp);
	}

	/* Điều chỉnh kích thước video xoay vòng */
	@SuppressLint("ShowToast")
	protected void setRatioVideoSize() {
		vSize = ++vSize % 3;
		switch (vSize) {
		// man hinh 4:3
		case 0:
			int h,
			w;
			txtTextZoom.setVisibility(View.VISIBLE);
			w = getWindowManager().getDefaultDisplay().getWidth();
			h = getWindowManager().getDefaultDisplay().getHeight();

			if (w > h) {
				w = (int) ((h / 3) * 4);
				setVideoSize(w, h);
			} else {
				h = (int) ((w / 3) * 4);
				setVideoSize(w, h);
			}
			txtTextZoom.setText("4:3");
			resize.setImageResource(R.drawable.btn_43scr);
			// Toast.makeText(Nahi_MediaActivity.this, "4:3",
			// Toast.LENGTH_SHORT);
			break;
		// man hinh 16:9
		case 1:
			txtTextZoom.setVisibility(View.VISIBLE);
			h = getWindowManager().getDefaultDisplay().getHeight();
			w = getWindowManager().getDefaultDisplay().getWidth();
			txtTextZoom.setText("16:9");
			if (w > h) {
				w = (int) ((h / 9) * 16);
				setVideoSize(w, h);

			} else {

				h = (int) ((w / 9) * 16);
				setVideoSize(w, h);

			}
			resize.setImageResource(R.drawable.btn_169scr);
			break;

		// man hinh fullscreen
		case 2:
			txtTextZoom.setVisibility(View.VISIBLE);
			setVideoSize(getWindowManager().getDefaultDisplay().getWidth(),
					getWindowManager().getDefaultDisplay().getHeight());
			txtTextZoom.setText("Toàn màn hình");
			resize.setImageResource(R.drawable.btn_fullscr);
			break;

		default:
			setVideoSize(getWindowManager().getDefaultDisplay().getWidth(),
					getWindowManager().getDefaultDisplay().getHeight());
			break;
		}

	}

	// load buffer truoc cho nhac, cung nhu la thoi gian cua video
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onPrepared called");
		btnPlayer.setVisibility(View.GONE);
		btnPlayer.setImageResource(R.drawable.btn_pause);
		progressBarWait.setVisibility(View.GONE);

		mIsVideoReadyToBePlayed = true;
		int millis = mMediaPlayer.getDuration();
		int hours = millis / (1000 * 60 * 60);
		int minutes = (millis % (1000 * 60 * 60)) / (1000 * 60);
		int seconds = ((millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000;

		if (hours > 0) {
			txtPercentEnd.setText(String.format("%02d:%02d:%02d", hours,
					minutes, seconds));

		} else {
			txtPercentEnd.setText(String.format("%02d:%02d", minutes, seconds));

		}
		if (mVideoWidth != 0 && mVideoHeight != 0) {

			mMediaPlayer.start();

		}

		// Get the SurfaceView layout parameters
		android.view.ViewGroup.LayoutParams lp = surface.getLayoutParams();
		lp.width = getWindowManager().getDefaultDisplay().getWidth();
		lp.height = getWindowManager().getDefaultDisplay().getHeight();
		// Commit the layout parameters
		surface.setLayoutParams(lp);

		if (mIsVideoReadyToBePlayed) {
			startVideoPlayback();
		}

	}// ket thuc ham

	@Override
	protected void onResume() {
		super.onResume();

	}

	//
	public void onCompletion(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCompletion called");

		btnPlayer.setVisibility(View.VISIBLE);
		stopThread();
		RegistrySession.getInstance(Nahi_MediaActivity.this).registrySession();

	}

	// Cap nhat phan tram cho seekbar
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub

		Log.d(TAG, "onBufferingUpdate percent:" + percent);
		seekBar.setSecondaryProgress(percent);

	}


	@Override
	protected void onPause() {
		super.onPause();
		releaseMediaPlayer();
		doCleanUp();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		releaseMediaPlayer();
		doCleanUp();
	}

	// giai phong video khoi bo nho
	private void releaseMediaPlayer() {
		if (mMediaPlayer != null) {
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

	//
	private void doCleanUp() {
		mVideoWidth = 0;
		mVideoHeight = 0;
		mIsVideoReadyToBePlayed = false;
		mIsVideoSizeKnown = false;
	}

	// Start Video
	private void startVideoPlayback() {
		Log.v(TAG, "startVideoPlayback");

		mMediaPlayer.start();

	}//

	//

	private Runnable hideController = new Runnable() {
		public void run() {
			hideAllLayout();
		}

	};

	// an tat cac layout
	protected void hideAllLayout() {
		hideControlOverlays();
		layoutSeekbar.setVisibility(View.GONE);
		layoutTop.setVisibility(View.GONE);
		layoutControl.setVisibility(View.GONE);
		layoutLike.setVisibility(View.GONE);
		txtTextZoom.setVisibility(View.GONE);
		btnPlayer.setVisibility(View.GONE);
		filmName.setVisibility(View.GONE);
		quality_of_films.setVisibility(View.GONE);
		filmName.clearAnimation();
		updateFullscreenStatus(true);

	}

	// goi su kien an voi thoi gian 5 giay neu nguoi dung ko tuong tac
	public void hideController() {

		handler.postDelayed(hideController, 7000);

	}

	// Hien lai video controller
	public void showController() {
		updateFullscreenStatus(false);
		if (mMediaPlayer.isPlaying()) {

			btnPlayer.setVisibility(View.GONE);

		} else {

			btnPlayer.setVisibility(View.VISIBLE);
		}
		filmName.startAnimation(animation);
		filmName.setVisibility(View.VISIBLE);
		quality_of_films.setVisibility(View.VISIBLE);
		layoutControl.setVisibility(View.VISIBLE);
		layoutSeekbar.setVisibility(View.VISIBLE);
		layoutTop.setVisibility(View.VISIBLE);
		btnPlayer.setVisibility(View.VISIBLE);
		handler.removeCallbacks(hideController);
		hideController();
		flagShow = true;

	}

	// Volume controller
	private void initVolumeController(int progress, SeekBar seek) {
		// Khai bao cac button
		try {

			seekBarVolume
					.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
						public void onStopTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
						}

						public void onStartTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
						}

						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {
							// TODO Auto-generated method stub
							volumePrgress = progress;
							audioManager.setStreamVolume(
									AudioManager.STREAM_MUSIC, progress, 0);
							if (progress == 0) {

								soundController
										.setImageResource((R.drawable.volumemute));

							} else {

								soundController
										.setImageResource((R.drawable.volume));

							}
							flagSound = false;
							// volumePrgress = progress;

						}
					});
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}// ket thuc ham seekbar audio

	/**
	 * OVERRIDE cac surface view
	 * 
	 * */
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		Log.d(TAG, "surfaceChange changed");
		Log.d("width__default__change:", String.valueOf(mVideoWidth));
		Log.d("height__default_change_:", String.valueOf(mVideoHeight));
		Log.d("______________________________", "___________");
		Log.d("width__default__change_arg2:", String.valueOf(arg2));
		Log.d("height__default_change_arg3:", String.valueOf(arg3));

	}

	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		Log.d(TAG, "surfaceCreated called");
		Log.d("width__default__created:", String.valueOf(mVideoWidth));
		Log.d("height__default_created_:", String.valueOf(mVideoHeight));
		// mMediaPlayer.setDisplay(holder);
		resumeDialog();
	}

	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		Log.d(TAG, "surfaceDestroy called");
		stopThread();
	}

	// /

	// Dieu chinh do sang man hinh
	public void setLight() {
		vLight = ++vLight % 3;
		int vL = 20 + vLight * 40;
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = vL / 100.0f;
		getWindow().setAttributes(lp);
	}

	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		Log.e(TAG, "onError--->   what:" + what + "    extra:" + extra);
		if (mMediaPlayer != null) {
			stopThread();
		}
		return false;
	}

	/**
	 * ham bat su kien tu key cua ban phim choi game cung nhu la ban phim remove
	 * tu remove, dieu chinh am thanh cung nhu la seekbar
	 * 
	 * @param keyCode
	 * @param event
	 * */

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		int keyCode = event.getKeyCode();
		switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_UP:
			// Do something to increase a value
			volumePrgress = volumePrgress + 1;
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
					volumePrgress, 0);
			soundController.setImageResource((R.drawable.volume));
			seekBarVolume.setProgress(volumePrgress);
			flagSound = false;
			return true;
			// // Do something to decrement a value
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			// Do something to decrease a value
			volumePrgress = volumePrgress - 1;
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
					volumePrgress, 0);
			seekBarVolume.setProgress(volumePrgress);
			if (volumePrgress == 0) {
				soundController.setImageResource((R.drawable.volumemute));
			}
			flagSound = false;
			return true;
			// volume muted
		case KeyEvent.KEYCODE_MUTE:
			bookAudio.addBookMark("Audio", volumePrgress);
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
			seekBarVolume.setProgress(0);
			return true;

		case KeyEvent.KEYCODE_HOME:
			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;
			//
		case KeyEvent.KEYCODE_DPAD_CENTER:
			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;
		case KeyEvent.KEYCODE_BACK:

			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;
			// case KeyEvent.KEYCODE_AVR_POWER:
		case paramConst.ENCLOSE_KEYCODE_AVR_POWER:
			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;

		case KeyEvent.KEYCODE_POWER:
			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;

		case paramConst.ENCLOSE_KEYCODE_ESCAPSE:
			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;

		default:
			return super.dispatchKeyEvent(event);
		}
	}

	//
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_MENU:

			try {
				bookVideo.addBookMark(filmInfo.FilmID,
						mMediaPlayer.getCurrentPosition());
				stopThread();

			} catch (Exception ex) {
				Log.d("TAG:::::::::_______", "Key code fail");
				ex.getMessage();

			}
			return true;

		}
		return false;
	}

	/**
	 * ket thuc ham bat nut ban phim
	 * */
	@Override
	public void onBackPressed() {
		try {
			bookVideo.addBookMark(filmInfo.FilmID,
					mMediaPlayer.getCurrentPosition());
			stopThread();

		} catch (Exception ex) {
			Log.d("TAG:::::::::_______", "can't send Intent");
			ex.getMessage();

		}

	}


	
	/*	Xu ly animation cho phan hien an cac layout */
	private void initAnimations() {

		final AnimationListener makeTopGone = new AnimationListener() {

			public void onAnimationStart(Animation animation) {
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
				Log.d(TAG, "onAnimationEnd - makeTopGone");
				layoutTop.setVisibility(View.GONE);
			}
		};

		final AnimationListener makeBottomGone = new AnimationListener() {

			public void onAnimationStart(Animation animation) {
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
				Log.d(TAG, "onAnimationEnd - makeBottomGone");
				layoutControl.setVisibility(View.GONE);
			}
		};

		final AnimationListener makeTopVisible = new AnimationListener() {

			public void onAnimationStart(Animation animation) {
				Log.d(TAG, "onAnimationStart - makeTopVisible");
				relay.setVisibility(View.VISIBLE);
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
			}
		};

		final AnimationListener makeBottomVisible = new AnimationListener() {

			public void onAnimationStart(Animation animation) {
				Log.d(TAG, "onAnimationStart - makeBottomVisible");
				layoutControl.setVisibility(View.VISIBLE);
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationEnd(Animation animation) {
			}
		};

		mSlideTopUpAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_top_up);
		mSlideBottomDownAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_bottom_down);
		mSlideTopUpAnimation.setAnimationListener(makeTopGone);
		mSlideBottomDownAnimation.setAnimationListener(makeBottomGone);

		mSlideTopDownAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_top_down);
		mSlideBottomUpAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_bottom_up);
		mSlideTopDownAnimation.setAnimationListener(makeTopVisible);
		mSlideBottomUpAnimation.setAnimationListener(makeBottomVisible);
	}

	private void hideControlOverlays() {
		Log.d(TAG, "hideControlOverlays");
		layoutTop.startAnimation(mSlideTopUpAnimation);
		layoutControl.startAnimation(mSlideBottomDownAnimation);
		
	}

	private void showControlOverlays() {
		Log.d(TAG, "showControlOverlays");
		layoutTop.startAnimation(mSlideTopDownAnimation);
		layoutControl.startAnimation(mSlideBottomUpAnimation);
		
	}
	
	/*	Ket thuc xu ly animation cho phan hien an cac layout */


}